package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.ResourceVo;
import com.zzyl.vo.TreeItemVo;
import com.zzyl.vo.TreeVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author xiao
 * @Date 2025/6/3 下午 9:56
 * @ClassName: ResourceService
 * @Desc:
 */
@Service
@RequiredArgsConstructor
public class ResourceServiceImpl implements ResourceService {

    private final ResourceMapper resourceMapper;

    /**
     * 获取资源列表
     *
     * @param resourceDto
     */
    @Override
    public List<ResourceVo> getResourceVoList(ResourceDto resourceDto) {

        List<Resource> resourceList = resourceMapper.getResourceVoList(resourceDto);
        if (CollUtil.isEmpty(resourceList)) {
            return List.of();
        }
        return BeanUtil.copyToList(resourceList, ResourceVo.class);


    }

    /**
     * 获取资源树形
     *
     * @param resourceDto
     */
    @Override
    public TreeVo resourceTreeVo(ResourceDto resourceDto) {
        ResourceDto dto = ResourceDto.builder()
                .dataState(SuperConstant.DATA_STATE_0)
                .parentResourceNo(NoProcessing.processString(SuperConstant.ROOT_PARENT_ID))
                .resourceType(SuperConstant.MENU)
                .build();
        List<Resource> resourceVoList = resourceMapper.getResourceVoList(dto);
        if (CollUtil.isEmpty(resourceVoList)) {
            throw new RuntimeException("资源获取异常");
        }
        // 构建根节点
        Resource rootResource = new Resource();
        rootResource.setResourceNo(SuperConstant.ROOT_PARENT_ID);
        rootResource.setResourceName("智慧养老院");
        // 构建集合
        List<TreeItemVo> treeItemVoList = new ArrayList<>();
        // 递归查询子节点
        recursionTreeVo(treeItemVoList, rootResource, resourceVoList);
        return TreeVo.builder().items(treeItemVoList).build();
    }


    /**
     * 递归查询子节点
     *
     * @param treeItemVoList
     * @param resource
     * @param resourceVoList
     */
    private void recursionTreeVo(List<TreeItemVo> treeItemVoList, Resource resource, List<Resource> resourceVoList) {
        // 构建当前资源
        TreeItemVo treeItemVo = TreeItemVo.builder()
                .id(resource.getResourceNo())
                .label(resource.getResourceName())
                .build();
        // 查询当前资源子资源
        List<Resource> childrenResources = resourceVoList.stream()
                .filter(r -> r.getParentResourceNo().equals(resource.getResourceNo()))
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(childrenResources)) {
            // 不为空,递归继续查询
            List<TreeItemVo> childrenTreeItemVoList = new ArrayList<>();
            childrenResources.forEach(r -> recursionTreeVo(childrenTreeItemVoList, r,resourceVoList ));

            treeItemVo.setChildren(childrenTreeItemVoList);
        }

        // 如果children为空,添加到集合
        treeItemVoList.add(treeItemVo);
    }

    /**
     * 创建资源
     *
     * @param resourceDto
     */
    @Override
    public void createResource(ResourceDto resourceDto) {
        //属性拷贝
        Resource resource = BeanUtil.copyProperties(resourceDto, Resource.class);
        // 数据状态与父资源保持一致
        Resource parentResource = resourceMapper.selectByResourceNo(resourceDto.getParentResourceNo());
        resource.setDataState(parentResource.getDataState());
        // 如果是按钮,就没用限制
        boolean isButton = false;
        if (resourceDto.getResourceType() != null && resourceDto.getResourceType().equals(SuperConstant.BUTTON)) {
            isButton = true;
        }
        // 创建资源
        String resourceNo = createResourceNo(resourceDto.getParentResourceNo(),isButton);
        resource.setResourceNo(resourceNo);
        //向数据库写入
        resourceMapper.insert(resource);
    }

    private String createResourceNo(String parentResourceNo, boolean isButton) {
        // 是否大于3级并且不是按钮
        if  ( !isButton && NoProcessing.processString(parentResourceNo).length() /3 >= 5 ){
            throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
        }
        // 创建资源编号
        // 父资源下是否有子资源
        ResourceDto dto = ResourceDto.builder().parentResourceNo(parentResourceNo).build();
        List<Resource> resourceList = resourceMapper.getResourceVoList(dto);
        //如果没用 直接新增
        if (CollUtil.isEmpty(resourceList)){
            return NoProcessing.createNo(parentResourceNo,true);
        }
        // 找到最大编号
        Long maxSize = resourceList.stream().map(r -> Long.valueOf(r.getResourceNo())).max(Comparator.comparing(i -> i)).get();
        return NoProcessing.createNo(maxSize.toString(),false);
    }
}
